<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Queue\Capsule\Manager;
use Session;
use DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Log;
use App\UserAccount;
use App\Coupon;
use App\UserCoupon;
use Illuminate\Support\Facades\Auth;

class UserAccountController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

	public function index(Request $request) {
		// 查看当前菜单可使用的功能按钮
		$uri = $request->path();
		$data['optionArr'] =  $this->checkMenuOption($uri);

		$phone = '';
    	if($request->input('phoneSearch')){
			$phone = trim($request->input('phoneSearch'));
	    }

		$userObj = UserAccount::getUserAccountList($phone);
//		dd($userObj);

		$data['userAccount'] = $userObj;
		$data['phoneS'] = $phone;

		return view('userAccount.list')->with($data);
	}



	public function show($id)
	{
		$userCar = UserAccount::getUserCarInfo($id);
		$userCoupons = UserAccount::getUserCoupons($id);
//		dd($userCoupons);

		$data['userCarInfo'] = $userCar;
		$data['userCouponInfo'] = $userCoupons;

		return view('userAccount.show')->with($data);

	}

	public function showOrder($id)
	{
		$userOrder = UserAccount::getUserOrder($id);
//		dd($userOrder);

		$data['userOrderInfo'] = $userOrder;

		return view('userAccount.showOrder')->with($data);

	}




	// 用户注册量统计
	public  function userAccountRegisterStatistics(Request $request){
		$where = array();
		// 日期
		if($request->validity){
			$choseTime = $request->validity;
			$validityArr = explode(' - ',$choseTime);
			$where['startTime'] = $validityArr[0];
			$where['endTime'] = $validityArr[1];
		}
		$userAccounts = array();
		$dataArr = array(); // 日期数组
		$regArr = array();   // 注册量数组
		$accountTotalList = UserAccount::getAccountRegisterTotal($where);
//			dd($accountTotalList);
		if($accountTotalList){
			$dateT = array(); // 折线图数据：开始、结束 日期数组
			$regTotalArr = array(); // 折线图数据：获取数
			foreach($accountTotalList as $key=>$value){
				$userAccounts[$key]['times'] = $value->times;
				$userAccounts[$key]['total'] = isset($value->accountTotal) ? $value->accountTotal : 0;  // 注册量

				// 获取时间数据：当前页两个时间
				if($key == 0){
					$dateT[] =  $value->times;
				}
				if($key == count($accountTotalList)-1){
					$dateT[] =  $value->times;
				}
				// 拼接获取数、消耗数 相关数组
				$regTotalArr[$key]['times'] = isset($value->times) ? $value->times : 0;   // 时间
				$regTotalArr[$key]['total'] = isset($value->accountTotal) ? $value->accountTotal : 0;   // 注册量
			}
			// 线形图数据---------------------------------------------------------------------------
			$curent_week = array();
			// 根据查询的结果数据组装相关参数值
			// 判断是否用了时间检索
			if($where){
				// 按照检索项目查找
				$i_ct = round((strtotime($where['endTime'])-strtotime($where['startTime']))/3600/24); // 计算开始到结束之间的天数
				// 拼接数组
				for($i=0;$i<=$i_ct;$i++){
					if($i==0){
						$curent_week[$i] = $where['startTime'];
					}
					$curent_week[$i] = date('Y-m-d',strtotime($where['startTime']."+".$i." day"));
				}
			}else{
				$start = $dateT[0];
				$end = $dateT[1];
				$i_ct = round((strtotime($end)-strtotime($start))/3600/24); // 计算开始到结束之间的天数
				// 时间数据值
				for($i=0;$i<=$i_ct;$i++){
					if($i==0){
						$curent_week[$i] = $dateT[0];
					}
					$curent_week[$i] = date('Y-m-d',strtotime($dateT[0]."+".$i." day"));
				}
			}
			//dd($curent_week);
			// 整理 日期、获取数、消耗数 的数组
			if($curent_week){
				foreach ($curent_week as $key=>$value) {
					$dataArr[] = str_replace('-', '月', substr($value, strpos($value, '-') + 1));
				}
				// 组装数据
				foreach ($curent_week as $key=>$value){
					// 下单量数组
					for($i=0;$i<count($regTotalArr);$i++){
						if(strtotime($value)==strtotime($regTotalArr[$i]['times'])){
							$regArr[$key] = (int)$regTotalArr[$i]['total'];
							break;
						}else{
							$regArr[$key]= 0;
						}
					}
				}
			}
		}
		$dataArr = json_encode($dataArr);
		$regArr = json_encode($regArr);
		$data['dataArr'] = $dataArr;
		$data['xdArr'] = $regArr;
		$data['userStatistics'] = $userAccounts;
//			dd($userAccounts);
		$data['validity'] = $request->validity;

		return view('userAccount.register_statistic')->with($data);

	}


	// 活跃用户管理
	public function getActiveUserManage(Request $request){
		// 查看当前菜单可使用的功能按钮
		$uri = $request->path();
		$data['optionArr'] =  $this->checkMenuOption($uri);

		$phone = '';
		$orderNum = '';
		if($request->input('phoneSearch')){
			$phone = trim($request->input('phoneSearch'));
		}
		if($request->input('orderNum')){
			$orderNum = trim($request->input('orderNum'));
		}
//		dd($orderNum);
		$activeUsers = UserAccount::getActiveUsersCount($phone,$orderNum);
//dd($activeUsers);

		$numArr = array(0=>'请选择',1,2,3,4,5,6,7,8,9,
		                 '10~20'=>'10~20',
		                 '20~30'=>'20~30',
		                 '30~40'=>'30~40',
		                 '40~50'=>'40~50',
		                 '50~100'=>'50~100',
		                 '100~500'=>'100~500',
		                 '500~1000'=>'500~1000',
		                 '1000~2000'=>'1000~2000',
		                 '2000~10000'=>'2000~10000'
		);
		$data['numArr'] = $numArr;
		$data['activeUsers'] = $activeUsers;
		$data['phoneS'] = $phone;
		$data['orderNumS'] = $orderNum;

		return view('userAccount.activeUsers')->with($data);

	}

	public function sendCouponToUser(Request $request){
		$userId = $request->id;
		// 获取用户手机号
//		$userInfo = UserAccount::find($userId);
		$userIdArr = explode(',',$userId);
		$userInfo = UserAccount::whereIn("phone", $userIdArr)->get();
//		dd($userInfo);
		foreach ($userInfo as $key=>$value){
			$user_openIdArr[] = $value->open_id;
			$user_phoneArr[] = $value->phone;
		}
		$user_openIds = implode(',',$user_openIdArr);
		$user_phones = implode(',',$user_phoneArr);
//		dd($user_openIds);

		// 获取所有优惠券
		$coupon = Coupon::where('is_del',1)->get();

		$data['coupon'] = $coupon;
		$data['user_openIds'] = $user_openIds;
		$data['user_phones'] = $user_phones;

		return view('userAccount.sendCoupon')->with($data);
	}

	public function sendCouponSave(Request $request){
		if(!$request->coupon_id) return -1;

//		return $request->coupon_id;
//		$coupon_id_arr = array(1); // 多个优惠券组成的数组
//		$openIdArr = array('dnfudjfnjd154dhqwzji');   //去重复用户组
//		$nums = array(2);  // 发送多张
//		$seTime = array("2017-09-17 00:00:00 ~ 2017-10-31 23:00:00");

		$coupon_id_arr = explode(',',$request->coupon_id); // 多个优惠券组成的数组
		$openIdArr = array_unique(explode(',',$request->open_id));   //去重复用户组
		$phonesArr = array_unique(explode(',',$request->phone));   // 去重用户组
		$nums = explode(',',$request->nums);  // 发送多张
		$seTime = explode(',',$request->seTime);
//		return $seTime;

		$dataArr = array();
		foreach($coupon_id_arr as $key=>$dcID){  // 遍历选中的每张优惠券
			for($i=0;$i<$nums[$key];$i++){//遍历每张优惠券发送的个数
				foreach($openIdArr as $k=>$userID){ // 需要发送的每个用户
					$dataArr[$key][$i][$k]['open_id'] = $userID;
					$dataArr[$key][$i][$k]['coupon_id'] = $dcID;
					$dataArr[$key][$i][$k]['useStatus'] = 1; // 0=未使用
					$dataArr[$key][$i][$k]['source'] = 1; // 1=系统赠送
					if(strpos($seTime[$key],' ~ ')){
						// 时间区段
						$dataArr[$key][$i][$k]['start_time'] = explode(' ~ ',$seTime[$key])[0];
						$dataArr[$key][$i][$k]['end_time'] = explode(' ~ ',$seTime[$key])[1];
					}else{
						// 月份
						if(is_numeric($seTime[$key])){
							$dataArr[$key][$i][$k]['start_time'] = date('Y-m-d H:i:s',time());
							$dataArr[$key][$i][$k]['end_time'] = date("Y-m-d H:i:s", strtotime("+$seTime[$key] months", time()));
						}
					}
				}
			}
		}

		$insertId = array();//发送成功
		$error = array();// 发送失败的用户
		foreach($dataArr as $key=>$dc){
			foreach($dc as $num){
				foreach($num as $k=>$insert){
					$couponU = new UserCoupon();
					$couponU->open_id =$insert['open_id'];
					$couponU->coupon_id =$insert['coupon_id'];
					$couponU->useStatus =$insert['useStatus'];
					$couponU->source =$insert['source'];
					if($insert['start_time']){
						$couponU->start_time =$insert['start_time'];
						$couponU->end_time =$insert['end_time'];
					}

					if($couponU->save()){
						$insertId[] = $couponU->id;
					}else{
						$error[] = $insert['open_id'];
					}
				}
			}
		}

		if($insertId){
			$adminUser = Auth::user();
			if($adminUser){
				$userId = $adminUser->id;
				$logs = $adminUser->name.'在'.date('Y-m-d H:i:s').'发送了优惠券';
				adminOperationLog($request,$userId,$logs);
			}

			return 1;
		}else{
			return -1;
		}

	}




}





